import { Button, Drawer} from 'antd';
import ProTable from '@ant-design/pro-table';
import React, { useImperativeHandle, useState} from 'react';
import type { ProColumns } from '@ant-design/pro-table';
import {hospitalDataById,addHospitalDetails} from '../../pages/MasterData/service';
import { message } from 'antd';
import { Popconfirm } from 'antd';
import DealerDialog from './DealerDialog';
import SaleDialog from './SaleDialog';


export type CustomerProps = {

};

const CustomerAuth: React.FC<CustomerProps> = React.forwardRef((props:any,ref:any)=>{
  const [dealers, setDealers] = useState<[]>([]);
  const [showDealer, setShowDealer] = useState(false);
  const [sales,setSales] = useState<any>([]);
  const [dealDialog,setDealDialog] = useState<boolean>(false);
  const [saleDialog,setSaleDialog] = useState<boolean>(false);
  const [hosId,setHosId]  = useState("");

  useImperativeHandle(ref,()=>({
    showAuth:(id:string)=>{
      setHosId(id);
      loadData(id);
    }
  }));

  const loadData=async(id:string)=>{
    var param = {id:id}
    var val =await hospitalDataById(param);
    if(val.errorCode==='200'){
      setShowDealer(true);
      setDealers(val.data.dealerList);
      setSales(val.data.salesCustomer);
    }else{
      message.error(val.errorMessage);
    }
  }

    const dealerColumns:ProColumns[] = [
      {
        title: '客户代码',
        dataIndex: 'loginName',
        width:100,
      },
      {
        title: '客户名称',
        dataIndex: 'cnName',
      },
      {
        title: '地区',
        dataIndex: 'provinces_label',
        renderText:(_,record:any)=>{
          return `${record.provinces_label}/${record.city_label}`;
        }
      },
      {
        fixed:'right',
        title: '操作',
        valueType: 'option',
        render: (text, record:any,_, action) => [
          <Popconfirm title='确定删除该客户吗?'     key='deleteDealer' onConfirm={() => {
              var data:any = dealers.filter((item:any) =>{ 
                return item.id!=record.id
              });
              setDealers(data);
          }}>
            <a>删除</a>
          </Popconfirm>
        ],
      }
    ]
  
    const contactColumn:ProColumns[] = [
      {
        title: '科室',
        dataIndex: 'dept',
        renderText:()=>'主管院领导'
      },
      {
        title: '姓名',
        dataIndex: 'aa',
        renderText:()=>{
          return '张XXX'
        }
      },
      {
        title: '联系电话',
        dataIndex: 'bb',
        renderText:()=>{
          return '187XXXXXXXX'
        }
      },
    ]

    const saleColumns:ProColumns[] = [
      {
        title: '销售',
        dataIndex: 'salesName',
      },
      {
        title: '角色',
        dataIndex: 'role',
        renderText:()=>'经理'
      },
      {
        title: '操作',
        fixed:'right',
        valueType: 'option',
        render: (text, record:any,_, action) => [
          <Popconfirm title='确定删除该销售吗?'     key='deleteSale' onConfirm={() => {
            var data:any = sales.filter((item:any) =>{ 
              return item.salesId!=record.salesId
            });
            setSales(data);
          }}>
            <a>删除</a>
          </Popconfirm>
        ],
      }
    ]
    
    return (
      <>
        <Drawer
              destroyOnClose={true}
              width={1000}
              title={'详情'}
              visible={showDealer}
              onClose={()=>{setShowDealer(false)}}
            >
              {/* <ProTable
                  headerTitle='客户列表'
                  size='small'
                  key='dealer'
                  toolbar={{ settings: [] }}
                  columns={dealerColumns}
                  dataSource={dealers}
                  rowKey='id'
                  pagination={false}
                  search={false}
                  toolBarRender={() => [
                    <Button
                      type='primary'
                      key='dealerBtn'
                      onClick={() => {
                        setDealDialog(true)
                      }}
                    >
                      选择客户
                    </Button>,
                  ]}
                >
              </ProTable> */}
              <ProTable
                  headerTitle='销售列表'
                  size='small'
                  key='sale'
                  toolbar={{ settings: [] }}
                  columns={saleColumns}
                  dataSource={sales}
                  rowKey='salesId'
                  pagination={false}
                  search={false}
                  toolBarRender={() => [
                    <Button
                      type='primary'
                      key='saleBtn'
                      onClick={() => {
                        setSaleDialog(true)
                      }}
                    >
                      选择销售
                    </Button>,
                  ]}
                >
              </ProTable>

              <ProTable
                  headerTitle='医院联系人'
                  size='small'
                  key='sale'
                  toolbar={{ settings: [] }}
                  columns={contactColumn}
                  dataSource={[{salesId:'111'}]}
                  rowKey='salesId'
                  pagination={false}
                  search={false}
                  toolBarRender={() => [
                    <Button
                      type='primary'
                      key='saleBtn'
                      onClick={() => {
                        setSaleDialog(true)
                      }}
                    >
                      新增
                    </Button>,
                  ]}
                >
              </ProTable>

              <div style={{margin:20}}>
                <Button type='primary' key='post' onClick={async()=>{
                  var param :any = {}
                  param['hospital'] = hosId
                  if(sales.length>0){
                    param['sales'] = sales.map((item:any)=>item.salesId)
                  }
                  param['dealer'] = []
                  dealers.forEach((item:any)=>{
                    param['dealer'].push({'dealerId':item.id});
                  });
                  var val = await addHospitalDetails(param);
                  if(val.errorCode==='200'){
                    message.success('提交成功');
                    setShowDealer(false)
                  }else{
                    message.error(val.errorMessage);
                  }
                }} >提交</Button>
              </div>
        </Drawer>
        <DealerDialog
            mode='mulit'
            onCancel={() => {
              setDealDialog(false)
            }}
            onSubmit={async (value) => {
              var data:any = [...dealers];
              var keys = dealers.map((item:any)=>{
                return item.id;
              });
              value.forEach((item:any)=>{
                if(keys.indexOf(item.id)<0){
                  data.push(item);
                }
              });
              // console.log(keys,value)
              setDealers(data);
              setDealDialog(false)
            }}
            modalVisible={dealDialog}
            values={[]}
           >
        </DealerDialog>
        <SaleDialog
            checkFlag = {true}
            onCancel={() => {
              setSaleDialog(false)
            }}
            onSubmit={async (value:any) => {             
             setSales([...sales,...value.map((item:any)=>{
              return {'salesName':item.name,'salesId':item.id,'teamId':item.teamId}
            })])
             setSaleDialog(false)
            }}
            modalVisible={saleDialog}
            values={sales.map((item:any)=>{
              return {id:item.salesId,teamId:item.teamId}
            })}
           >
        </SaleDialog>
        
      </>
    );
  
});

export default CustomerAuth;